<template>
    <div ref="ce"></div>
</template>

<script setup lang="ts">
import { EditorView, basicSetup } from 'codemirror'
import { json } from '@codemirror/lang-json'

const emits = defineEmits(['update:value'])
const props = defineProps<{
    value?: string
}>()

const ce = ref<Element>()
const view = ref<EditorView>()

onMounted(() => {
    initEditor()
})
onUnmounted(() => {
    destroyEditor()
})

const initEditor = () => {
    const editor = new EditorView({
        doc: props.value,
        parent: unref(ce),
        extensions: [
            basicSetup,
            json(),
            change,
        ]
    })
    view.value = editor
}
const destroyEditor = () => {
    unref(view).destroy()
}
const change = EditorView.updateListener.of((v) => {
    emits('update:value', v.state.doc.toString())
})

</script>
